﻿using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EntityGraph.SQL
{
    internal class QueryPlan
    {
        public IEnumerable<SqlSelect> Queries { get; private set; }
        public IEnumerable<TypeTree> TypeTrees { get; private set; }
        public IEnumerable<EntityGraphPath> Paths { get; private set; }
        private List<SQLParameterBinding> _bindings = new List<SQLParameterBinding>();
        public List<SQLParameterBinding> Bindings { get { return _bindings; } }
        public string CommandText { get; private set; }
        public QueryPlan(IEnumerable<SqlSelect> queries, IEnumerable<EntityGraphPath> paths, IEnumerable<TypeTree> typeTrees)
        {
            this.Queries = queries;
            this.Paths = paths;
            this.TypeTrees = typeTrees;
            StringBuilder sb = new StringBuilder();
            foreach(var q in queries)
            {
                q.ToStringBuilder(sb);
            }
            CommandText = sb.ToString();
        }
        public void Bind(object entity)
        {
            Bindings.Clear();
            int i = 0;
            foreach(var path in Paths)
            {
                var query = Queries.ElementAt(i) as SqlSelectFromTableWithParameterBinding;
                if(query != null)
                {
                    var binding = query.Bind(path, entity);
                    if(binding != null && Bindings.Any(b => b.Parameter.Name == binding.Parameter.Name) == false)
                    {
                        Bindings.Add(binding);
                    }
                }
                i++;
            }
        }
    }
}
